package com.lv.service.ui

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SizeUtils
import com.lv.common.base.BaseActivity
import com.lv.common.imp.OnPositionTListener
import com.lv.common.utils.ARoutUtils
import com.lv.common.widget.recyclerview.decoration.SpacesItemDecoration
import com.lv.service.R
import com.lv.service.adapter.CanlenderSelectedAdapter
import com.lv.service.bean.CommonSelectedBean
import com.lv.service.databinding.ActivityCalenderBinding
import com.lv.service.weidget.canlender.DateAndTimeUtil
import com.lv.service.weidget.canlender.DayAdapter
import com.lv.service.weidget.canlender.DayBean
import java.text.SimpleDateFormat
import java.util.*

/**
 * 作者： ygx
 * 创建日期：2023/5/6 1:35 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：公共 开关页面
 */
@Route(path = ARoutUtils.CalenderActivity)
class CalenderActivity : BaseActivity<ActivityCalenderBinding>(),
    View.OnClickListener {
    @Autowired(name = "startDate")//标题
    @JvmField
    var startDate: String = ""

    @Autowired(name = "endDate")//内容
    @JvmField
    var endDate: String = ""

    @Autowired(name = "isShowMouth")//开关状态
    @JvmField
    var isShowMouth: Boolean = false

    @Autowired(name = "isShowSelected")//开关状态
    @JvmField
    var isShowSelected: Boolean = false

    @Autowired(name = "port")//开关状态
    @JvmField
    var mPortBeans: ArrayList<CommonSelectedBean>? = null
    private val dataList = mutableListOf<DayBean>()

    private var toDayData = "" //今天的日期

    private var currentData = "" //选择的日期

    private var nowYear = 2023 //今天的月份

    private var nowMouth = 1 //今天的月份

    private var nowDay = 1 //今天是多少号

    private var adapter: DayAdapter? = null
    private var mPortAdapter: CanlenderSelectedAdapter? = null
    private var isFisrtComming = true
    override fun getLayoutRes() = R.layout.activity_calender
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            rlParent.setOnClickListener(this@CalenderActivity)
            tvSure.setOnClickListener(this@CalenderActivity)
            tvCancel.setOnClickListener(this@CalenderActivity)
            tvCurrentMouth.setOnClickListener(this@CalenderActivity)
//            StatusBarUtil.setHeightAndPadding(this@CalenderActivity, titleBar)

        }
    }


    override fun initConfig() {
        super.initConfig()
        // 初始化适配器
        initAdapter()
        if (isShowSelected) {
            mBinding.rvPort.visibility = View.VISIBLE
            intitLinkLayout()
            initAdapterEvent()
        }
    }

    private fun initAdapterEvent() {
        mPortAdapter?.mPositionTListener = OnPositionTListener { position, data ->
            val selectedItem: Boolean = mPortBeans!![position].selected
            var count = 0
            var positionLast = -1
            for (i in mPortBeans!!.indices) {
                val selected: Boolean = mPortBeans!![i].selected
                if (selected) {
                    count++
                    positionLast = i
                }
            }
            if (count > 1) {
                mPortBeans!![position].selected = !selectedItem
                mPortAdapter?.notifyItemChanged(position)
            } else {
                if (positionLast == position) {
                    return@OnPositionTListener
                } else {
                    mPortBeans!![position].selected = (!selectedItem)
                    mPortAdapter?.notifyItemChanged(position)
                }
            }
        }

    }


    private fun intitLinkLayout() {
//        mPortBeans?.clear()
//        val mPort: ArrayList<CommonSelectedBean>? = intent.getParcelableArrayListExtra("seleced")
//        if (!mPort.isNullOrEmpty()) {
//            mPortBeans.addAll(mPort)
//        }
        val staggeredPortManager =
            StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
        mBinding.rvPort.layoutManager = staggeredPortManager
        mPortAdapter = CanlenderSelectedAdapter(mPortBeans)
        mBinding.rvPort.adapter = mPortAdapter
        mBinding.rvPort.addItemDecoration(
            SpacesItemDecoration(
                SizeUtils.dp2px(14.0f),
                SizeUtils.dp2px(0.0f), false
            )
        )
    }

    override fun initData() {
        super.initData()

    }

    override fun initEvents() {
        super.initEvents()
        mBinding.llCalender.setOnTouchListener(View.OnTouchListener { v, event -> true })

    }

    private fun initAdapter() {
        adapter = DayAdapter(dataList, this@CalenderActivity)
        mBinding.gv.adapter = adapter

        // 拿到日历对象，动态设置时间
        // 使用日历对象可以帮我们避免一些问题，如 月数 的临界点问题，到的 12 月是再加 1 的话会自动
        // 帮我们加到下一年去，同理从 1 月到 12 月也一样。
        val calendar = Calendar.getInstance()
        toDayData =
            calendar[Calendar.YEAR].toString() + "/" + (calendar[Calendar.MONTH] + 1) + "/" + calendar[Calendar.DAY_OF_MONTH]
        nowYear = calendar[Calendar.YEAR]
        nowMouth = calendar[Calendar.MONTH] + 1
        nowDay = calendar[Calendar.DAY_OF_MONTH]
        if (TextUtils.isEmpty(startDate) || TextUtils.isEmpty(endDate) || startDate == endDate) {
            endDate = ""
        }
        if (TextUtils.isEmpty(startDate)) {
            startDate = toDayData
        }
        var year: Int = nowYear
        var i: Int = nowMouth
        try {
            year = startDate.split("/").toTypedArray()[0].toInt()
            i = startDate.split("/").toTypedArray()[1].toInt()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        if (nowYear > year) {
            mBinding.ivNextMonth.isEnabled = true
        } else {
            mBinding.ivNextMonth.isEnabled = i < nowMouth
        }
        setCurrentData(calendar)
        updateAdapter(calendar, dataList, adapter)
        mBinding.ivPreMonth.setOnClickListener(View.OnClickListener {
            calendar[Calendar.MONTH] = calendar[Calendar.MONTH] - 1
            updateAdapter(calendar, dataList, adapter)
            val ii = calendar[Calendar.MONTH] + 1
            val years = calendar[Calendar.YEAR]
            if (nowYear > years) {
                mBinding.ivNextMonth.isEnabled = true
            } else {
                mBinding.ivNextMonth.isEnabled = ii <= nowMouth
            }
            //                String time = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月";
        })
        mBinding.ivNextMonth.setOnClickListener(View.OnClickListener {
            calendar[Calendar.MONTH] = calendar[Calendar.MONTH] + 1
            updateAdapter(calendar, dataList, adapter)
            val ii = calendar[Calendar.MONTH] + 1
            val years = calendar[Calendar.YEAR]
            if (nowYear > years) {
                mBinding.ivNextMonth.isEnabled = true
            } else {
                mBinding.ivNextMonth.isEnabled = ii <= nowMouth
            }

//                String time = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月";
//                tv_time.setText("您" + time + "累计行走");
        })
        adapter?.setOnDataItemOnClickInterface(object : DayAdapter.DataItemOnClickInterface {
            override fun onItemClickListener(data: String?, bean: DayBean?) {
                val selectedIs: Boolean = DateAndTimeUtil.isDateOneBigger(data, toDayData)
                if (selectedIs) {
                    Toast.makeText(this@CalenderActivity, "日期选择有误", Toast.LENGTH_SHORT).show()
                    return
                }
                isShowMouth = false

//                if (dateBean.getItemType() == DayBean.item_type_month || TextUtils.isEmpty(dateBean.getDay())) {
//                    return;
//                }

                //这个是在Dialog显示的情况下会用到，来判断如期是否已选完，来改变Dialog里面确定按钮的选中状态
//                if(onDateSelected!=null){
//                    onDateSelected.hasSelect(false);
//                }
                //如果没有选中开始日期则此次操作选中开始日期
                if (startDate == "") {
                    startDate = data ?: ""
                } else if (startDate == data) { //开始和结束为同一天
//                    startDate = data;
                    endDate = ""
                } else if (endDate == "") {
                    //如果选中了开始日期但没有选中结束日期，本次操作选中结束日期

                    //如果当前点击的结束日期跟开始日期一致 则不做操作
                    val dateOneBigger: Boolean = DateAndTimeUtil.isDateOneBigger(startDate, data)
                    if (startDate === data) {
                    } else if (dateOneBigger) {
                        //如果当前点选的日期小于当前选中的开始日期，则本次操作重新选中开始日期
                        endDate = startDate
                        startDate = data ?: ""
                    } else {
                        //当前点选的日期大于当前选中的开始日期  此次操作选中结束日期
                        endDate = data ?: ""
                    }
                } else if (startDate != "" && endDate != "") {
                    //结束日期和开始日期都已选中
//                    clearState();//取消选中状态
                    startDate = data ?: ""
                    endDate = ""
                    for (i in dataList.indices) {
                        dataList.get(i).setItemState(DayBean.ITEM_STATE_NORMAL)
                    }
                    /**
                     * 一定要先清除结束日期，再重新选择开始日期，不然会有一个bug，当开始日期和结束日期都选中的时候，如果此次点选开始日期，则选中开始日期，
                     * 如果点结束日期，则全都清除了，再点结束日期没有反应，应该是结束日期变为开始日期才对
                     * 因此要先清除结束位置，再重新选中开始日期
                     */
                    //一定要先清除结束日期，再重新选择开始日期
//                    endDate.setItemState(DayBean.ITEM_STATE_NORMAL);
//                    endDate = null;
//                    startDate.setItemState(DayBean.ITEM_STATE_NORMAL);
//                    startDate = dateBean;
//                    startDate.setItemState(DayBean.ITEM_STATE_BEGIN_DATE);
                }
                for (k in dataList.indices) {
                    val dateStr: String = dataList[k].getDateStr()
                    if (dateStr == startDate) {
                        dataList[k].setItemState(DayBean.ITEM_STATE_BEGIN_DATE)
                    }
                    if (dateStr == endDate) {
                        dataList[k].setItemState(DayBean.ITEM_STATE_END_DATE)
                    }
                    if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                        val dateOneBigger: Boolean =
                            DateAndTimeUtil.isDateOneBigger(dateStr, startDate)
                        val dateOneBigger1: Boolean =
                            DateAndTimeUtil.isDateOneBigger(endDate, dateStr)
                        if (dateOneBigger && dateOneBigger1) {
                            dataList[k].setItemState(DayBean.ITEM_STATE_SELECTED)
                        }
                        dataList[k].isSelectedFinsh = true
                    } else {
                        if (dateStr == startDate) {
                            dataList[k].setItemState(DayBean.ITEM_STATE_BEGIN_DATE)
                        } else {
                            dataList[k].setItemState(DayBean.ITEM_STATE_NORMAL)
                        }
                        dataList[k].isSelectedFinsh = false
                    }
                }
                adapter?.notifyDataSetChanged()
            }

        })
    }

    private fun updateAdapter(
        calendar: Calendar,
        dataList: MutableList<DayBean>,
        adapter: DayAdapter?
    ) {
        dataList.clear()
        // 最后将日期设为当月 有选中，再设为选中的月
        var year = calendar[Calendar.YEAR]
        var month = calendar[Calendar.MONTH]
        if (isFisrtComming && !TextUtils.isEmpty(startDate)) {
            try {
                year = startDate.split("/").toTypedArray()[0].toInt()
                month = startDate.split("/").toTypedArray()[1].toInt()
            } catch (e: Exception) {
                e.printStackTrace()
            }
            isFisrtComming = false
        }
        calendar[Calendar.YEAR] = year
        calendar[Calendar.MONTH] = month - 1
        setCurrentData(calendar)
        // 得到本月一号的星期索引
        // 索引从 1 开始，第一个为星期日,减1是为了与星期对齐，如星期一对应索引1，星期二对应索引二
        calendar[Calendar.DAY_OF_MONTH] = 1
        var weekIndex = calendar[Calendar.DAY_OF_WEEK] - 1


        // 将日期设为上个月
        calendar[Calendar.MONTH] = calendar[Calendar.MONTH] - 1
        val preMonthDays = getMonth(
            calendar[Calendar.MONTH] + 1,
            calendar[Calendar.YEAR]
        )
        // 拿到上一个月的最后几天的天数
        for (i in 0 until weekIndex) {
            val bean = DayBean()
            bean.setYear(calendar[Calendar.YEAR])
            bean.setMonth(calendar[Calendar.MONTH] + 1)
            bean.setDay(preMonthDays - weekIndex + i + 1)
            bean.setCurrentDay(false)
            bean.setCurrentMonth(false)
            dataList.add(bean)
        }

        // 将日期设为当月
        calendar[Calendar.MONTH] = calendar[Calendar.MONTH] + 1
        val currentDays = getMonth(
            calendar[Calendar.MONTH] + 1,
            calendar[Calendar.YEAR]
        )
        // 拿到当月的天数
        for (i in 0 until currentDays) {
            val bean = DayBean()
            bean.setYear(calendar[Calendar.YEAR])
            bean.setMonth(calendar[Calendar.MONTH] + 1)
            bean.setDay(i + 1)
            // 当前日期
            val nowDate = getFormatTime("yyyy/M/d", Calendar.getInstance().time)
            // 选择的日期
            val selectDate = getFormatTime("yyyy/M/", calendar.time) + (i + 1)
            // 假如相等的话，那么就是今天的日期了
            if (nowDate.contentEquals(selectDate)) {
                bean.setCurrentDay(true)
            } else {
                bean.setCurrentDay(false)
            }
            bean.setDateStr(selectDate)
            bean.setCurrentMonth(true)
            dataList.add(bean)
        }

        // 拿到下个月第一周的天数
        // 先拿到下个月第一天的星期索引
        // 之前设为了1号，所以将日历对象的月数加 1 就行了
        calendar[Calendar.MONTH] = calendar[Calendar.MONTH] + 1
        weekIndex = calendar[Calendar.DAY_OF_WEEK] - 1
        for (i in 0 until 7 - weekIndex) {
            val bean = DayBean()
            bean.setYear(calendar[Calendar.YEAR])
            bean.setMonth(calendar[Calendar.MONTH] + 1)
            bean.setDay(i + 1)
            bean.setCurrentDay(false)
            bean.setCurrentMonth(false)
            dataList.add(bean)
        }
        for (i in dataList.indices) {
            dataList[i].setItemState(DayBean.ITEM_STATE_NORMAL)
            val s: String = "${dataList[i].year}/${dataList[i].month}/${dataList[i].day}"
            dataList[i].dateStr = s
            if (s == startDate) {
                dataList[i].setItemState(DayBean.ITEM_STATE_BEGIN_DATE)
            }
            if (s == endDate) {
                dataList[i].setItemState(DayBean.ITEM_STATE_END_DATE)
            }
            if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                val dateOneBigger: Boolean = DateAndTimeUtil.isDateOneBigger(s, startDate)
                val dateOneBigger1: Boolean = DateAndTimeUtil.isDateOneBigger(endDate, s)
                if (dateOneBigger && dateOneBigger1) {
                    dataList[i].setItemState(DayBean.ITEM_STATE_SELECTED)
                }
                dataList[i].setSelectedFinsh(true)
            } else {
                if (s == startDate) {
                    dataList[i].setItemState(DayBean.ITEM_STATE_BEGIN_DATE)
                } else {
                    dataList[i].setItemState(DayBean.ITEM_STATE_NORMAL)
                }
                dataList[i].setSelectedFinsh(false)
            }
        }
        adapter?.notifyDataSetChanged()
        // 最后将日期设为当月 有选中，再设为选中的月
//        int month = calendar.get(Calendar.MONTH) - 1;
//        if (isFisrtComming && !TextUtils.isEmpty(startDate)) {
//            try {
//                month = Integer.parseInt(startDate.split("/")[1]);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            isFisrtComming = false;
//        }
//        calendar.set(Calendar.MONTH, month);
    }

    // 设置当前的时间
    private fun setCurrentData(calendar: Calendar) {
        mBinding.tvCurrentDate.text=(calendar[Calendar.YEAR].toString() + "-" + (calendar[Calendar.MONTH] + 1))
        currentData =
            calendar[Calendar.YEAR].toString() + "-" + (calendar[Calendar.MONTH] + 1) + "-" + calendar[Calendar.DAY_OF_MONTH]
    }

    // 判断是否为闰年
    fun isRunYear(y: Int): Boolean {
        return y % 4 == 0 && y % 100 != 0 || y % 400 == 0
    }

    // 格式化时间，设置时间很方便，也比较简单，学的很快
    fun getFormatTime(p: String?, t: Date?): String {
        return SimpleDateFormat(p, Locale.CHINESE).format(t)
    }

    // 传入年和月得出当月的天数
    fun getMonth(m: Int, y: Int): Int {
        return when (m) {
            2 -> if (isRunYear(y)) 29 else 28
            4, 6, 9, 11 -> 30
            else -> 31
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_cancel, R.id.rl_parent -> {
                finish()
            }
            R.id.tv_sure -> {
                if (TextUtils.isEmpty(startDate)) {
                    Toast.makeText(this, "请选择开始日期", Toast.LENGTH_SHORT).show()
                    return
                }

                if (TextUtils.isEmpty(endDate)) {
                    endDate = startDate
                }
                val intent = Intent()
                intent.putExtra("startDate", startDate)
                intent.putExtra("endDate", endDate)
                intent.putExtra("isShowMouth", isShowMouth)
                intent.putParcelableArrayListExtra("port", mPortBeans)

                setResult(RESULT_OK, intent)
                finish()
            }

            R.id.tv_current_mouth -> {
                isShowMouth = true
                var maxDay = DateAndTimeUtil.getMonthMaxDay(currentData)
                val split = currentData.split("-").toTypedArray()
                startDate = split[0] + "/" + split[1] + "/" + 1
                if (nowMouth.toString() + "" == split[1]) {
                    maxDay = nowDay.toString() + ""
                }
                endDate = split[0] + "/" + split[1] + "/" + maxDay
                for (i in dataList.indices) {
                    val dateStr = dataList[i].dateStr
                    if (dateStr == startDate) {
                        dataList[i].setItemState(DayBean.ITEM_STATE_BEGIN_DATE)
                    }
                    if (dateStr == endDate) {
                        dataList[i].setItemState(DayBean.ITEM_STATE_END_DATE)
                    }
                    if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                        val dateOneBigger = DateAndTimeUtil.isDateOneBigger(dateStr, startDate)
                        val dateOneBigger1 = DateAndTimeUtil.isDateOneBigger(endDate, dateStr)
                        if (dateOneBigger && dateOneBigger1) {
                            dataList[i].setItemState(DayBean.ITEM_STATE_SELECTED)
                        }
                        dataList[i].isSelectedFinsh = true
                    } else {
                        if (dateStr == startDate) {
                            dataList[i].setItemState(DayBean.ITEM_STATE_BEGIN_DATE)
                        } else {
                            dataList[i].setItemState(DayBean.ITEM_STATE_NORMAL)
                        }
                        dataList[i].isSelectedFinsh = false
                    }
                }
                adapter?.notifyDataSetChanged()
            }


        }
    }

    //    override fun onBackPressed() {
//        super.onBackPressed()
//        exitProcess(0)
//    }
//
//
//    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit()
//            return false
//        }
//        return super.onKeyDown(keyCode, event)
//    }
//
//    private fun exit() {
////        intent.putExtra("isOpen", mIsOpen)
////        setResult(Activity.RESULT_OK, intent)
//        finish()
//    }
    override fun finish() {
        super.finish()
        overridePendingTransition(0, 0)
    }
}
